<script setup lang="ts" name="HealthEvaluation">
import {computed, onActivated, onBeforeMount, reactive, ref, watch} from 'vue'
import addGuide from '@/views/pages/physicalExaminationManager/physicalKnowlege/manage/addGuide.vue'
import {
  getHealthyAppraiseInfo,
  InforSummaryList,
  inforSummaryData,
  getHealthEvaluation,
  HealthEvaluation,
  saveHealthEvaluation,
  smartEva,
  SmartEva,
  HealthEvaluationParams
} from '@/api/medicalExaminerDesk/beginPhysicalExamination/healthEvaluation'
import {ChecksOrRadios} from '@/api/medicalExaminerDesk/beginPhysicalExamination'
import {ElMessage, FormRules} from 'element-plus/es'
import useUser from '@/store/user'
import {NotLeadingAndTrailingSpaces} from '@/util/common'
const user = useUser.setup().store

const props = defineProps({
  // 体检登记表id
  checkupRegisterId: {
    type: String,
    required: true,
    default: ''
  },
  // 禁止编辑
  disEdit: {
    type: Boolean,
    required: true,
    default: false
  },
  // 性别
  gender: {
    type: String,
    required: false,
    default: ''
  }
})

// 保存和拒检的加载
const showSaveLoading = ref<boolean>(false)

//显示弹窗
const showDialog = ref<boolean>(false)

defineEmits(['dutyDoctorName', 'disEdit'])

// 体检是否有异常输入框禁用
const abnormalDisabled = ref<boolean>(false)

// 健康评价
const healthEvaluationForm = reactive<HealthEvaluation>({
  abnorSign: '', // 健康评价
  healthGuide: '', // 健康指导
  riskControl: '', // 危险因素控制
  abnormal: '1', // 体检有无异常
  evaluationCheckbox: [], // 健康评价
  abnormalOne: '', // 异常1
  abnormalTwo: '', // 异常1
  abnormalThree: '', // 异常1
  abnormalFour: '', // 异常1
  healthCoaching: [], // 健康指导
  riskFactorControlCheckbox: [], // 危险因素控制
  vaccinesInfo: '', // 建议接种疫苗
  otherInfo: '', // 其他危险因素控制
  guideSelected: [], // 健教指导勾选
  guideValue: '' // 健教指导内容
})

// 体检大类的体检医生姓名
const dutyDoctorName11 = computed(() => {
  return healthEvaluationForm.dutyDoctorName || (user.userInfor?.jobName === '医生' ? user.userInfor?.userName : '')
})

// 健康智能评价数据
const smartEvaData = ref<Array<SmartEva>>([])

// 建教指导内容 ，json数据
const guideData = ref()

// 健康评价
const evaluationCheckboxs: Array<ChecksOrRadios> = [
  {label: '健康或良好', value: '3'},
  {label: '一般或较弱', value: '4'},
  {label: '患有慢性病', value: '5'},
  {label: '有生理缺陷', value: '6'},
  {label: '身体有残疾', value: '7'}
]

// 健康指导
const healthCoachingCheckboxs: Array<ChecksOrRadios> = [
  {label: '纳入慢性患者健康管理', value: '1'},
  {label: '建议复查', value: '2'},
  {label: '建议转诊', value: '3'}
]

// 危险因素控制
const riskFactorControlCheckboxs: Array<ChecksOrRadios> = [
  {label: '戒烟', value: '1'},
  {label: '健康饮酒', value: '2'},
  {label: '饮食', value: '3'},
  {label: '锻炼', value: '4'}
]

// 信息总结基础数据
const inforSummaryList = reactive<Array<InforSummaryList>>(inforSummaryData)

// 表单实例
const formRef = ref()

// 表单校验规则
const rules = computed<FormRules>(() => {
  return {
    // 异常1
    abnormalOne: [
      {pattern: NotLeadingAndTrailingSpaces, message: '首尾不能为空格！', trigger: ['change', 'blur']},
      {max: 100, message: '最多100个字符！', trigger: ['change', 'blur']}
    ],
    // 异常2
    abnormalTwo: [
      {pattern: NotLeadingAndTrailingSpaces, message: '首尾不能为空格！', trigger: ['change', 'blur']},
      {max: 100, message: '最多100个字符！', trigger: ['change', 'blur']}
    ],
    // 异常3
    abnormalThree: [
      {pattern: NotLeadingAndTrailingSpaces, message: '首尾不能为空格！', trigger: ['change', 'blur']},
      {max: 100, message: '最多100个字符！', trigger: ['change', 'blur']}
    ],
    // 异常4
    abnormalFour: [
      {pattern: NotLeadingAndTrailingSpaces, message: '首尾不能为空格！', trigger: ['change', 'blur']},
      {max: 100, message: '最多100个字符！', trigger: ['change', 'blur']}
    ],
    // 建议接种疫苗
    vaccinesInfo: [
      {pattern: NotLeadingAndTrailingSpaces, message: '首尾不能为空格！', trigger: ['change', 'blur']},
      {max: 100, message: '最多100个字符！', trigger: ['change', 'blur']}
    ],
    // 其他信息
    otherInfo: [
      {pattern: NotLeadingAndTrailingSpaces, message: '首尾不能为空格！', trigger: ['change', 'blur']},
      {max: 100, message: '最多100个字符！', trigger: ['change', 'blur']}
    ]
  }
})

/**
 * @description: 更新健教指导内容
 * @param {*} data // JSON数据，包括勾选id和文本框数据
 * @return {*}
 */
const updateGuideCheckboxValue = (data) => {
  guideData.value = data //保存json数据
  healthEvaluationForm.guideSelected =
    JSON.parse(data)?.selected?.filter((item) => {
      return !!item
    }) || [] //勾选id
  healthEvaluationForm.guideValue = JSON.parse(data)?.text || '' // 文本内容
}

/**
 * @description: 获取左侧信息总结
 * @return {*}
 */
const getInformationSummary = () => {
  getHealthyAppraiseInfo(props.checkupRegisterId).then((res) => {
    const {data} = res.data
    data &&
      inforSummaryList.forEach((item) => {
        const record = data[item.key] // 当前键对应的体检大类VO的值
        record &&
          item.data.forEach((el) => {
            el.value = record[el.key] // 体检项目的键对应体检大类下面的值
            // 近一年是否曾醉酒转换
            el.key === 'drunkState' && (el.value = el.value === '1' ? '是' : el.value === '2' ? '否' : '')
            // 职业病危害因素接触史转换
            el.key === 'occupaHist' && (el.value = el.value === '1' ? '无' : el.value === '2' ? '有' : '')
          })
      })
  })
}

/**
 * @description: 获取健康评价
 * @return {*}
 */
const getInitData = () => {
  props.checkupRegisterId &&
    getHealthEvaluation(props.checkupRegisterId)
      .then((res) => {
        const {data} = res.data
        // 浅拷贝
        Object.assign(healthEvaluationForm, data)
        healthEvaluationForm.abnormal = data?.abnorSign?.split('|')[0] || '1' // 健康评价单选
        healthEvaluationForm.evaluationCheckbox = data?.abnorSign?.split('|').slice(1) || [] // 健康评价多选
        healthEvaluationForm.healthCoaching = data?.healthGuide?.split('|') || [] //健康指导
        healthEvaluationForm.riskFactorControlCheckbox = data?.riskControl?.split('|') || [] // 危险因素控制
        guideData.value = JSON.stringify({selected: data?.guideGrade?.split('|') || [], text: data?.guideValue || ''}) // 建教指导内容
        healthEvaluationForm.guideSelected =
          data?.guideGrade?.split('|')?.filter((item) => {
            return !!item
          }) || [] // 建教指导内容勾选
      })
      .finally(() => {
        showSaveLoading.value = false
      })
}

/**
 * @description: 保存
 * @return {*}
 */
const onSave11 = () => {
  formRef.value &&
    formRef.value.validate((valid: boolean, fields) => {
      if (valid) {
        showSaveLoading.value = true
        const params: HealthEvaluationParams = {
          id: healthEvaluationForm.id, // 表单Id
          checkupRegisterId: props.checkupRegisterId, // 体检登记表id
          dutyDoctorId: healthEvaluationForm.dutyDoctorId || user.userInfor?.id, // 体检医生id
          dutyDoctorName: healthEvaluationForm.dutyDoctorId !== user.userInfor?.id ? healthEvaluationForm.dutyDoctorName || user.userInfor?.userName : user.userInfor?.userName, // 体检医生姓名
          checkupStatus: 2, // 已检
          abnorSign: healthEvaluationForm.abnormal + `${healthEvaluationForm.evaluationCheckbox?.length ? '|' : ''}${healthEvaluationForm.evaluationCheckbox?.join('|')}`, //健康评价
          abnormalOne: healthEvaluationForm.abnormalOne || null, // 异常1
          abnormalTwo: healthEvaluationForm.abnormalTwo || null, // 异常1
          abnormalThree: healthEvaluationForm.abnormalThree || null, // 异常1
          abnormalFour: healthEvaluationForm.abnormalFour || null, // 异常1
          healthGuide: healthEvaluationForm.healthCoaching?.join('|') || null, // 健康指导
          riskControl: healthEvaluationForm.riskFactorControlCheckbox?.join('|') || null, //危险因素控制
          targetWeight: healthEvaluationForm.riskFactorControlCheckbox?.indexOf('5') !== -1 ? healthEvaluationForm.targetWeight : undefined, // 目标体重
          vaccinesInfo: healthEvaluationForm.riskFactorControlCheckbox?.indexOf('6') !== -1 ? healthEvaluationForm.vaccinesInfo || null : null, // 建议接种疫苗信息
          otherInfo: healthEvaluationForm.riskFactorControlCheckbox?.indexOf('7') !== -1 ? healthEvaluationForm.otherInfo || null : null, //其他信息
          guideGrade: healthEvaluationForm.guideSelected?.join('|') || null, // 健教指导勾选
          guideValue: healthEvaluationForm.guideValue || null, // 健教指导内容
          abnormalId:
            smartEvaData.value
              .map((item) => {
                return item.id
              })
              .join(',') || null //健康智能评价数据
        }
        saveHealthEvaluation(params)
          .then(() => {
            getInitData()
            ElMessage.success('保存成功!')
          })
          .catch((err) => {
            showSaveLoading.value = false
            console.warn(err)
          })
      } else {
        console.warn(fields)
      }
    })
}

/**
 * @description: 智能评价
 * @return {*}
 */
const onIntelligentEvaluation = () => {
  showSaveLoading.value = true
  smartEva(props.checkupRegisterId)
    .then((res) => {
      const data = res.data?.data || []
      smartEvaData.value = data // 保存智能评价信息
      // 有异常的评价信息
      const abnormalData = res.data?.data?.filter((item) => {
        return item.isException === true
      })
      // 如果有数据就代表有异常
      healthEvaluationForm.abnormal = abnormalData?.length ? '2' : '1' // 数据就代表有异常
      //健康指导
      let healthCoachingArr: Array<string> = []
      // 危险因素控制勾选先拼接,后逗号分隔
      let dangerousControlArr: Array<string> = []
      // 建议接种疫苗信息,先拼接，再逗号分隔
      const vaccinesInfoArr: Array<string> = []
      //其他信息,先拼接，再逗号分隔
      const otherInfoArr: Array<string> = []
      // 健教指导内容,先合并在逗号分隔
      const guideValueArr: Array<string> = []
      let guideGradeArr: Array<string> = []
      let abnormal = '' // 异常信息拼接，用于计算长度
      let abnormalOne = '' // 异常1
      let abnormalTwo = '' // 异常2
      let abnormalThree = '' // 异常3
      let abnormalFour = '' // 异常4
      abnormalData.forEach((item) => {
        // 不管是否纳入异常都记录异常
        abnormal += item.name + ','
        // 拼接异常信息，超出100个字符拼接到下一个Input框
        if (abnormal.length <= 100) {
          abnormalOne += item.name + ',' // 异常1
        } else if (abnormal.length - abnormalOne.length <= 100) {
          abnormalTwo += item.name + ',' // 异常2
        } else if (abnormal.length - abnormalOne.length - abnormalTwo.length <= 100) {
          abnormalThree += item.name + ',' // 异常3
        } else {
          abnormalFour += item.name + ',' // 异常4
        }
        //健康指导
        item?.healthGuide && (healthCoachingArr = healthCoachingArr.concat(item?.healthGuide?.split(',') || []))
        // 危险因素控制JSON
        const dangerousControl = JSON.parse(item?.dangerousControl)
        dangerousControl?.selected && (dangerousControlArr = dangerousControlArr.concat(dangerousControl?.selected)) //危险因素控制勾选
        dangerousControl?.vaccines_info && vaccinesInfoArr.push(dangerousControl?.vaccines_info) // 建议接种疫苗信息
        dangerousControl?.other_info && otherInfoArr.push(dangerousControl?.other_info) //其他信息
        // 健教指导JSON
        const guideGrade = JSON.parse(item?.guideCheckboxValue)
        // 建教指导内容勾选合并去重
        guideGradeArr = guideGradeArr.concat(guideGrade?.selected)
        guideGrade?.text && guideValueArr.push(guideGrade?.text)
      })
      healthEvaluationForm.abnormalOne = abnormalOne.slice(0, -1) // 异常1,删除最后的逗号
      healthEvaluationForm.abnormalTwo = abnormalTwo.slice(0, -1) // 异常2
      healthEvaluationForm.abnormalThree = abnormalThree.slice(0, -1) // 异常3
      healthEvaluationForm.abnormalFour = abnormalFour.slice(0, -1) // 异常4
      //健康指导
      healthEvaluationForm.healthCoaching = healthCoachingArr.length
        ? Array.from(new Set([...healthCoachingArr]))?.filter((item) => {
          return !!item
        })
        : []
      //危险因素控制勾选
      healthEvaluationForm.riskFactorControlCheckbox = dangerousControlArr.length
        ? Array.from(new Set([...dangerousControlArr]))?.filter((item) => {
          return !!item
        })
        : []
      // 建议接种疫苗信息
      healthEvaluationForm.vaccinesInfo = vaccinesInfoArr.join(',')
      //其他信息
      healthEvaluationForm.otherInfo = otherInfoArr.join(',')
      // 建教指导内容勾选,去掉空数据
      healthEvaluationForm.guideSelected = Array.from(new Set([...guideGradeArr]))?.filter((item) => {
        return !!item
      })
      // 健教指导内容
      healthEvaluationForm.guideValue = guideValueArr.join(',')
      // 建教指导组件数据
      guideData.value = JSON.stringify({selected: healthEvaluationForm.guideSelected, text: healthEvaluationForm.guideValue || ''}) // 建教指导内容
      ElMessage.success('智能评价成功!')
    })
    .catch((err) => {
      console.warn(err)
      smartEvaData.value = []
    })
    .finally(() => {
      showSaveLoading.value = false
    })
}

watch(
  () => healthEvaluationForm.abnormal,
  (value) => {
    // 体检无异常，清空异常
    if (value === '1') {
      abnormalDisabled.value = true
      delete healthEvaluationForm.abnormalOne
      delete healthEvaluationForm.abnormalTwo
      delete healthEvaluationForm.abnormalThree
      delete healthEvaluationForm.abnormalFour
    } else {
      abnormalDisabled.value = false
    }
  }
)

onBeforeMount(() => {
  getInitData()
  getInformationSummary()
})

onActivated(() => {
  getInformationSummary()
})
</script>
<template>
  <div class="health-evaluation d-common-flex-full d-check-up-desk-content">
    <div class="information-summary">
      <div class="title d-common-flex-algin-center">
        信息总结
      </div>
      <div class="information-summary-box">
        <el-scrollbar class="information-summary-scrollbar" :always="true" wrap-class="d-common-post-abs d-common-full">
          <el-collapse>
            <el-collapse-item v-for="item in inforSummaryList" :key="item.key" :title="`【${item.title}】`">
              <ul>
                <li v-for="el in item.data" :key="el.key">
                  {{ el.label }}：{{ el.value }}{{ el.value ? el.unit : '' }}
                </li>
              </ul>
            </el-collapse-item>
          </el-collapse>
        </el-scrollbar>
      </div>
    </div>
    <div class="evaluation">
      <el-form ref="formRef" label-position="top" :model="healthEvaluationForm" :rules="rules" :disabled="disEdit">
        <el-form-item label="健康评价" class="health-evaluation-form-item">
          <el-radio-group v-model="healthEvaluationForm.abnormal">
            <el-radio label="1">
              体检无异常
            </el-radio>
            <el-radio label="2">
              体检有异常
            </el-radio>
          </el-radio-group>
          <el-form-item prop="evaluationCheckbox" class="evaluation-checkbox">
            <el-checkbox-group v-model="healthEvaluationForm.evaluationCheckbox">
              <el-checkbox v-for="item in evaluationCheckboxs" :key="item.value" :label="item.value">
                {{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <div class="inline-form">
            <el-form-item label="异常1：" class="inline-input-item" prop="abnormalOne">
              <el-input v-model="healthEvaluationForm.abnormalOne" clearable :disabled="abnormalDisabled" />
            </el-form-item>
            <el-form-item label="异常2：" class="inline-input-item" prop="abnormalTwo">
              <el-input v-model="healthEvaluationForm.abnormalTwo" clearable :disabled="abnormalDisabled" />
            </el-form-item>
            <el-form-item label="异常3：" class="inline-input-item" prop="abnormalThree">
              <el-input v-model="healthEvaluationForm.abnormalThree" clearable :disabled="abnormalDisabled" />
            </el-form-item>
            <el-form-item label="异常4：" class="inline-input-item" prop="abnormalFour">
              <el-input v-model="healthEvaluationForm.abnormalFour" clearable :disabled="abnormalDisabled" />
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item label="健康指导" prop="healthCoaching" class="health-evaluation-form-item">
          <el-checkbox-group v-model="healthEvaluationForm.healthCoaching">
            <el-checkbox v-for="item in healthCoachingCheckboxs" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="危险因素控制" prop="riskFactorControlCheckbox" class="health-evaluation-form-item risk-factor-control">
          <el-checkbox-group v-model="healthEvaluationForm.riskFactorControlCheckbox">
            <el-checkbox v-for="item in riskFactorControlCheckboxs" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-checkbox>
            <el-checkbox label="5">
              减体重
            </el-checkbox>
            <el-form-item v-show="healthEvaluationForm.riskFactorControlCheckbox.indexOf('5') !== -1" prop="targetWeight" class="target-weight">
              （目标 <el-input-number v-model="healthEvaluationForm.targetWeight" :controls="false" :precision="2" :max="999" />kg）
            </el-form-item>
            <div class="inline-form">
              <el-checkbox label="6">
                建议接种疫苗
              </el-checkbox>
              <el-form-item v-show="healthEvaluationForm.riskFactorControlCheckbox.indexOf('6') !== -1" prop="vaccinesInfo" style="margin-left: 10px">
                <el-input v-model="healthEvaluationForm.vaccinesInfo" clearable />
              </el-form-item>
            </div>
            <div class="inline-form">
              <el-checkbox label="7">
                其他
              </el-checkbox>
              <el-form-item v-show="healthEvaluationForm.riskFactorControlCheckbox.indexOf('7') !== -1" prop="otherInfo" style="margin-left: 10px">
                <el-input v-model="healthEvaluationForm.otherInfo" clearable />
              </el-form-item>
            </div>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <el-button class="health-education-guidance-btn" @click="showDialog = true">
        健教指导
      </el-button>
    </div>
  </div>
  <add-guide v-if="showDialog" :show-dialog="showDialog" :data="guideData" :disabled="disEdit" @close="showDialog = false" @update-guide-checkbox-value="updateGuideCheckboxValue" />
  <div class="d-check-up-desk-footer d-common-flex-center d-common-width-full">
    <span class="doctor">体检医生：</span>
    <el-input v-model="dutyDoctorName11" disabled />
    <el-button type="primary" :loading="showSaveLoading" :disabled="disEdit" @click="onIntelligentEvaluation()">
      智能评价
    </el-button>
    <el-button type="primary" :loading="showSaveLoading" :disabled="disEdit" @click="onSave11()">
      保存
    </el-button>
  </div>
</template>
<style scoped lang="less">
.information-summary {
  flex: 1;
  min-width: 350px;
  max-width: 450px;
  margin-right: 30px;
  border: 1px solid #dddddd;
  .title {
    height: 32px;
    padding-left: 19px;
    background: rgba(204, 204, 204, 0.55);
    font-weight: bold;
  }
}
.information-summary-box {
  padding: 15px 12px;
  ul {
    list-style: none;
    padding: 0;
    li {
      padding: 3px 10px;
      color: #333333;
    }
  }
  .information-summary-scrollbar {
    height: 66vh;
  }
}
.evaluation {
  flex: 1.9;
}
.el-collapse {
  border-bottom: none;
}
:deep(.el-collapse-item__wrap) {
  border-bottom: none;
}
.el-collapse-item {
  margin-bottom: 8px;
}
:deep(.el-collapse-item__header) {
  height: 32px;
  background: rgba(204, 204, 204, 0.55);
  padding-left: 15px;
}

.health-evaluation-form-item {
  padding-bottom: 18px;
  margin-bottom: 18px;
  border-bottom: 1px solid rgba(195, 201, 210, 1);
  :deep(.el-form-item__label) {
    color: var(--d-font-color-text);
    font-weight: bold;
    display: inline-flex;
    align-items: center;
  }
  :deep(.el-form-item__content) {
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
  }
}

.inline-input-item {
  margin-bottom: 12px;
  :deep(.el-form-item__label) {
    font-weight: normal;
    margin: 0 !important;
  }
  :deep(.el-form-item__content) {
    margin: 0;
  }
  .el-input {
    width: 600px;
    height: 32px;
    margin: 0 5px;
  }
}

.evaluation-checkbox {
  margin-bottom: 16px;
}
.risk-factor-control {
  .el-input-number {
    width: 80px;
    height: 32px;
    margin: 0 5px;
  }
  .el-input {
    width: 300px;
    height: 32px;
  }
  .el-checkbox {
    margin-bottom: 15px;
  }
}
.health-education-guidance-btn {
  color: var(--theme-color);
  border: 1px solid var(--theme-color);
}
.inline-form {
  max-width: 800px;
  .el-form-item {
    display: inline-flex;
    vertical-align: middle;
    margin-bottom: 15px;
  }
  :deep(.el-form-item__label) {
    justify-content: flex-start;
    width: 65px;
  }
}
.target-weight {
  display: inline-flex;
  :deep(.el-form-item__content) {
    flex-direction: row;
  }
}
</style>
